package com.cdwm.mrp.common.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdwm.mrp.common.tools.JwtHelper;
import com.cdwm.mrp.domain.po.User;
import com.cdwm.mrp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/4
 *
 * 实现token验证的过滤器
 * 该类继承OncePerRequestFilter，顾名思义，它能够确保在一次请求中只通过一次filter
 * 该类使用JwtTokenUtils工具类进行token校验
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter  {

    @Autowired
    private UserMapper userMapper;

    //@Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        //获取request token
        String token  = httpServletRequest.getHeader("token");
        if (Objects.nonNull(token) && !Objects.equals("",token)) {
            String userName = JwtHelper.getUserName(token);
            if (userName !=null && "".equals(userName)) {
                User user = userMapper.selectOne( new QueryWrapper<User>().lambda().eq(User::getUsername,userName));
                if (user!=null){
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                }else {
                    throw new MissingCsrfTokenException("token令牌是假冒的");
                }
            }else {
                throw new MissingCsrfTokenException("token令牌错误");
            }

        }else {
            throw new MissingCsrfTokenException("没有token令牌");
        }


    }
}
